package com.szl.group.controller;

import com.szl.group.common.enums.ResultCodeEnum;
import com.szl.group.common.model.R;
import com.szl.group.utils.VerificationCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 逻辑待完善。。
 *
 * @author zhangchao
 */

@Controller
@RequestMapping("/")
@Api(tags = {"登录"})
@Slf4j
public class LoginController {


    @Autowired
    private VerificationCode verificationCode;

    @ApiOperation(value = "登录")
    @PostMapping(value = "/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password") String password) {

        String s = SecurityContextHolder.getContext().getAuthentication().toString();
        System.out.println(s);
//    public R doLogin(@RequestParam("username") String username, @RequestParam("password") String password) {
//        UserDto userDto = userService.login(username, password);
//        UserDto userDto = userService.login(authenticationDTO.getUsername(), authenticationDTO.getPassword());
        return "redirect:/index.html";
    }

    @ApiOperation(value = "session失效")
    @RequestMapping(value = "/invalid", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public R invalid() {
        return R.fail(ResultCodeEnum.NONCE_EXPIRED, "session已过期");
    }

    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public R logout() {
        return R.success(200, "退出登录成功");
    }


    @GetMapping("")
    public String login() {
        return "redirect:/login.html";
    }


    @GetMapping("/image/code")
    public void getVerifyCode(HttpServletResponse response, HttpServletRequest request) throws IOException {

        response.setContentType("image/jpeg");
        String code = verificationCode.drawImage(response);
        //将字符保存到session中用于前端的验证
        request.getSession().setAttribute("verify_code", code);

    }
}
